import { Button, Card, Cascader, message, Select, Table } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React, { PureComponent } from 'react';
import enums from '../enums';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import Ellipsis from '../../../components/Ellipsis';
import AddModal from './addModal';
import DetailModal from './detailModal';
import EditModal from './editModal';
import styles from './index.less';
import { PlusOutlined } from '@ant-design/icons';
import { filterAuth } from '@/support/common';
import MaskText from '@/components/MaskText';

const { Option } = Select;

class RiskImpleRule extends PureComponent {
  state = {
    addModalVisible: false,
    editModalVisible: false,
    editModalData: null,
    detailModalVisible: false,
    detailModalData: null,
    tableData: [],
    curPage: 1,
    pageSize: 10,
    businessCode: '',
    total: 0,
    tableLoading: false,
    enable: undefined,
    orgId: null,
    orgOptions: [],
    // riskVehicle: {},
    // overdueVehicle: {},
    // allVehicle: {},
    riskEventList: [],
    riskEventUuid: undefined,
    autoRiskData: null,
  };

  componentDidMount() {
    this.handleTableData();
    this.handleGetOrgTree();
    this.handleGetAutoRisk();
    this.handleGetriskEventList();
  }

  handleGetAutoRisk = () => {
    this.props.dispatch({
      type: 'riskImpleRule/getDataWithRes',
      payload: {
        url: '/mscreditbusiness/merchants/autorisk',
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          // if (response.data && response.data.length > 0) {
          //   let riskVehicle = {};
          //   let overdueVehicle = {};
          //   let allVehicle = {};
          //   response.data.map((e) => {
          //     if (e.type === 'risk_vehicle') {
          //       riskVehicle = e;
          //     }
          //     if (e.type === 'overdue_vehicle') {
          //       overdueVehicle = e;
          //     }
          //     if (e.type === 'all_vehicle') {
          //       allVehicle = e;
          //     }
          //   });
          //   this.setState({
          //     riskVehicle,
          //     overdueVehicle,
          //     allVehicle,
          //   });
          // }
          this.setState({ autoRiskData: response.data });
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  handleGetOrgTree = () => {
    this.props.dispatch({
      type: 'http/getData',
      payload: {
        url: '/org/findorglistbytoken',
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          this.setState({
            orgOptions: response.data,
          });
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  // 异常事件
  handleGetriskEventList = () => {
    this.props.dispatch({
      type: 'riskImpleRule/postObjWithRes',
      payload: {
        url: '/mscreditbusiness/event/page',
        curPage: 1,
        pageSize: 1000,
        enable: enums.riskEventEnable.effective.value,
      },
      callback: response => {
        this.setState({
          riskEventList: response.data?.rows || [],
        });
      },
    });
  };
  handleTableData = () => {
    const { curPage, pageSize, enable, orgId, riskEventUuid } = this.state;
    this.setState({
      tableLoading: true,
    });
    this.props.dispatch({
      type: 'riskImpleRule/postObjWithRes',
      payload: {
        url: '/mscreditbusiness/rule/page',
        ...{ curPage, pageSize, enable, orgId, riskEventUuid },
      },
      callback: response => {
        if (response && response.statusCode == '0' && response.data) {
          if (response.data.rows.length === 0 && response.data.pagination.current > 1) {
            this.setState(
              {
                curPage: 1,
                pageSize: 10,
              },
              () => {
                this.handleTableData();
              },
            );
          } else {
            this.setState({
              tableData: response.data.rows,
              total: response.data.pagination.total,
            });
          }
        } else {
          if (response.statusCode !== '0') {
            message.error(response.statusMessage);
          }
        }
        this.setState({
          tableLoading: false,
        });
      },
    });
  };

  handleDetail = record => {
    this.setState({
      detailModalVisible: true,
      detailModalData: record,
    });
  };

  handleEdit = record => {
    this.setState({
      editModalVisible: true,
      editModalData: record,
    });
  };
  handleDelete = uuid => {
    this.props.dispatch({
      type: 'riskImpleRule/postObjWithRes',
      payload: {
        url: '/mscreditbusiness/rule/delete',
        uuid,
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          this.handleTableData();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  handleEnable = uuid => {
    this.props.dispatch({
      type: 'riskImpleRule/postDataWithRes',
      payload: {
        url: '/mscreditbusiness/rule/enable',
        uuid,
        enable: enums.riskRuleEnable.effective.value,
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          this.handleTableData();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  handleDisable = uuid => {
    this.props.dispatch({
      type: 'riskImpleRule/postDataWithRes',
      payload: {
        url: '/mscreditbusiness/rule/enable',
        uuid,
        enable: enums.riskRuleEnable.disable.value,
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          this.handleTableData();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  handleAdd = () => {
    this.setState({
      addModalVisible: true,
    });
  };

  handleReset = () => {
    this.setState(
      {
        enable: undefined,
        orgId: null,
        curPage: 1,
        pageSize: 10,
        riskEventUuid: undefined,
      },
      () => {
        this.handleTableData();
      },
    );
  };

  handleSearch = () => {
    this.handleTableData();
  };

  changeAddModalVisible = flag => {
    if (flag) {
      //TODO:请求接口刷新数据
      this.handleTableData();
      this.setState({
        addModalVisible: false,
      });
    } else {
      this.setState({
        addModalVisible: false,
      });
    }
  };

  changeEditModalVisible = flag => {
    if (flag) {
      //TODO:请求接口刷新数据
      this.handleTableData();
      this.setState({
        editModalVisible: false,
        editModalData: null,
      });
    } else {
      this.setState({
        editModalVisible: false,
        editModalData: null,
      });
    }
  };

  changeDetailModalVisible = flag => {
    this.setState({
      detailModalVisible: false,
      detailModalData: null,
    });
  };

  render() {
    const {
      tableData,
      addModalVisible,
      editModalVisible,
      editModalData,
      detailModalVisible,
      detailModalData,
      total,
      tableLoading,
      curPage,
      pageSize,
      enable,
      orgId,
      orgOptions,
      // riskVehicle,
      // overdueVehicle,
      // allVehicle,
      riskEventList,
      riskEventUuid,
      autoRiskData,
    } = this.state;
    const {
      riskImpleRule: {
        pageData: { rows },
      },
      loading,
      dispatch,
      permissions,
      location: { pathname = '/' },
    } = this.props;
    // const detailBtnAuth = this.context.authButton.includes(
    //   'thirdOrgCreditVehicleRiskImpleRule-detail',
    // );
    // const detailBtnAuth = filterAuth('riskImpleRule-detail', permissions, pathname);
    // const editBtnAuth = filterAuth('riskImpleRule-edit', permissions, pathname);
    // const deleteBtnAuth = filterAuth('riskImpleRule-delete', permissions, pathname);
    // const enableBtnAuth = filterAuth('riskImpleRule-enable', permissions, pathname);
    // const disableBtnAuth = filterAuth('riskImpleRule-disable', permissions, pathname);

    const columns = [
      {
        title: '风控规则',
        dataIndex: 'riskRuleName',
        render: text => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '风控触发事件',
        dataIndex: 'riskEventContent',
        render: (text, record) => (
          <div
            style={{
              color:
                record.riskEventEnable == enums.riskEventEnable.disable.value
                  ? 'rgb(240,102,0)'
                  : '',
            }}
          >
            <Ellipsis length={15} tooltip>
              {text}
            </Ellipsis>
          </div>
        ),
      },
      {
        title: '风控实施规则',
        dataIndex: 'riskControlResult',
        render: text => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '生效状态',
        dataIndex: 'enable',
        render: text => {
          let findText = enums.riskRuleEnable.array.find(e => e.value === text);
          return findText ? findText.label : text;
        },
      },
      {
        title: '风控对象',
        dataIndex: 'orgName',
        render: text => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        render(val) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        render: text => {
          if (text) {
            return moment(text).format('YYYY-MM-DD HH:mm:ss');
          }
        },
      },
      {
        title: '操作',
        dataIndex: 'uuid',
        fixed: 'right',
        render: (text, record) => {
          const btns = [];
          const detailBtn = {
            title: '查看',
            key: 'detailBtn',
            auth: 'riskImpleRule-detail',
            onConfirm: () => this.handleDetail(record),
          };
          const editBtn = {
            title: '修改',
            key: 'edit',
            auth: 'riskImpleRule-edit',
            onConfirm: () => this.handleEdit(record),
          };
          const deleteBtn = {
            title: '删除',
            Popconfirm: true,
            message: '确认要删除吗?',
            key: 'delete',
            auth: 'riskImpleRule-delete',
            onConfirm: () => this.handleDelete(text),
          };
          const enableBtn = {
            title: '启用',
            Popconfirm: true,
            message: '确认要启用吗?',
            key: 'enable',
            auth: 'riskImpleRule-enable',
            onConfirm: () => this.handleEnable(text),
          };
          const disableBtn = {
            title: '停用',
            Popconfirm: true,
            message: '确认要停用吗?',
            key: 'disable',
            auth: 'riskImpleRule-disable',
            onConfirm: () => this.handleDisable(text),
          };
          //是否被已经生效的预警信息使用
          const isRiskWarnMsgEffective = record.riskWarnMsgEnable
            ? record.riskWarnMsgEnable == enums.warnMsgEnable.effective.value
            : true;
          //关联的异常事件是否生效
          const isRiskEventEffective =
            record.riskEventEnable == enums.riskEventEnable.effective.value;
          btns.push(detailBtn);
          // 非系统预设
          if (!record.isSystem) {
            if (record.enable === enums.riskRuleEnable.ineffective.value) {
              //如果关联的预警信息已生效或者异常事件已生效
              if (isRiskWarnMsgEffective && isRiskEventEffective) {
                btns.push(enableBtn);
                btns.push(editBtn);
              }
              btns.push(deleteBtn);
            }
            if (record.enable === enums.riskRuleEnable.effective.value) {
              btns.push(disableBtn);
            }
            if (record.enable === enums.riskRuleEnable.disable.value) {
              //如果关联的预警信息已生效或者异常事件已生效
              if (isRiskWarnMsgEffective && isRiskEventEffective) {
                btns.push(enableBtn);
                btns.push(editBtn);
              }
            }
          } else {
            //  预设的预警信息操作区只有修改按钮
            btns.push(editBtn);
          }
          return <PateoAuthButtons btns={btns} max={3} pathname={pathname} />;
        },
      },
    ];
    const pagination = {
      showSizeChanger: true,
      total: total,
      current: curPage,
      pageSize: pageSize,
      size: 'small',
      showTotal: () => {
        return <span>共&nbsp;{total}&nbsp;条</span>;
      },
    };

    const tableProps = {
      columns,
      pagination,
      rowKey: 'uuid',
      scroll: { x: 'max-content' },
      loading: tableLoading,
      dataSource: tableData,
      onChange: pagination => {
        this.setState(
          {
            curPage: pagination.current,
            pageSize: pagination.pageSize,
          },
          () => {
            this.handleTableData();
          },
        );
      },
    };

    return (
      <div>
        <div className={styles.pateoSearch}>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>生效状态:</div>
            <Select
              placeholder="请选择生效状态"
              value={enable}
              onChange={e => {
                this.setState({
                  enable: e,
                });
              }}
            >
              {enums.riskRuleEnable.array.map(e => {
                return (
                  <Option key={e.value} value={e.value}>
                    {e.label}
                  </Option>
                );
              })}
            </Select>
          </div>

          <div className={styles.searchCascaderStr}>
            <div className={styles.title}>风控对象:</div>
            <Select
              placeholder="请选择风控对象"
              value={orgId}
              onChange={e => {
                this.setState({
                  orgId: e,
                });
              }}
            >
              {orgOptions.map(org => {
                return (
                  <Option key={org.sid} value={org.sid}>
                    {org.orgName}
                  </Option>
                );
              })}
            </Select>
          </div>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>异常事件:</div>
            <Select
              placeholder="请选择异常事件"
              value={riskEventUuid}
              onChange={e => {
                this.setState({
                  riskEventUuid: e,
                });
              }}
            >
              {riskEventList?.map(riskEvent => {
                return (
                  <Option key={riskEvent.uuid} value={riskEvent.uuid}>
                    {riskEvent.riskEventContent}
                  </Option>
                );
              })}
            </Select>
          </div>
          <div className={styles.searchBtn}>
            <Button
              onClick={() => this.handleSearch()}
              type={'primary'}
              size="small"
              style={{ marginRight: '10px' }}
            >
              查询
            </Button>
            <Button size="small" onClick={() => this.handleReset()}>
              重置
            </Button>
          </div>
        </div>

        <Card bordered={false} style={{ marginTop: 10 }}>
          {filterAuth('riskImpleRule-add', permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                icon={<PlusOutlined />}
                size="small"
                type="primary"
                onClick={() => this.handleAdd()}
              >
                新建风控实施规则
              </Button>
            </div>
          ) : null}
          <Table {...tableProps} />
        </Card>
        {addModalVisible ? (
          <AddModal
            autoRiskData={autoRiskData}
            orgOptions={orgOptions}
            changeAddModalVisible={this.changeAddModalVisible}
          />
        ) : null}
        {editModalVisible ? (
          <EditModal
            autoRiskData={autoRiskData}
            orgOptions={orgOptions}
            editModalData={editModalData}
            changeEditModalVisible={this.changeEditModalVisible}
          />
        ) : null}
        {detailModalVisible ? (
          <DetailModal
            autoRiskData={autoRiskData}
            orgOptions={orgOptions}
            detailModalData={detailModalData}
            changeDetailModalVisible={this.changeDetailModalVisible}
          />
        ) : null}
      </div>
    );
  }
}
export default connect(state => {
  return {
    loading: state.loading.effects['riskImpleRule/postFetchPage'],
    permissions: state?.menu?.permissions,
    riskImpleRule: state.riskImpleRule,
  };
})(RiskImpleRule);
